"""
使用urllib2请求隧道服务器
请求http和https网页均适用
"""
import urllib.request
import ssl
import time

# 应用账号（请替换为真实账号）
app_key = 'app_key'
# 应用密码（请替换为真实密码）
app_secret = 'app_secret'

proxy_host = "http-dynamic.xiaoxiangdaili.com"
proxy_port = 10030


def getUrlContent(target_url):
    proxyMeta = "http://%(user)s:%(pass)s@%(host)s:%(port)s" % {
        "user": app_key,
        "pass": app_secret,
        "host": proxy_host,
        "port": proxy_port,
    }
    proxies = {
        'http': proxyMeta,
        'https': proxyMeta,
    }
    try:
        # 使用代理IP发送请求
        proxy_support = urllib.request.ProxyHandler(proxies)
        opener = urllib.request.build_opener(proxy_support)
        urllib.request.install_opener(opener)
        response = urllib.request.urlopen(target_url)
    except Exception as e:
        print(e)
    else:
        print(response.read())

# 全局取消证书验证，避免访问https网页报错
ssl._create_default_https_context = ssl._create_unverified_context

target_url = "http://httpbin.org/ip"
for i in range(5):
    getUrlContent(target_url)
    time.sleep(10)